package Day2025_02_22;

public class MyBlockingQueue {
    private int[] elementData;
    private volatile int head;
    private volatile int tail;
    private volatile int size;

    public MyBlockingQueue (int capacity) {
        if (capacity <= 0) {
            throw new RuntimeException("队列容量必须大于0");
        }
        elementData = new int[capacity];
    }

    public synchronized void put (int value) throws InterruptedException {
        synchronized (this) {
            while (size >= elementData.length) this.wait();
        }
        elementData[tail++] = value;
        size++;
        if (tail >= elementData.length) tail = 0;
        notifyAll();
    }

    public synchronized int take () throws InterruptedException {
        synchronized (this) {
            while (size <= 0) this.wait();
        }
        int value = elementData[head++];
        size--;
        if (head >= elementData.length) head = 0;
        notifyAll();
        return value;
    }
}
